// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
    env: 'cloud1-4gqogyksa87ef4e2'
});
const db = cloud.database();
const wqb_questions = db.collection('wqb_questions'); // 存放错题
const wqb_grade = db.collection('wqb_grade'); // 年级里的错题数据库
const _ = db.command;
const $ = db.command.aggregate
// 云函数入口函数
exports.main = async (event, context) => {
    const { scene } = event;
    // 场景
    return new Promise(async (reslove, reject) => {
        // 场景为录入错题，SAVE_QUESTION
        if (scene === 'SAVE_QUESTION') {
            const { gid, enterObj, className, gradeDesc, uid } = event;
            const { type, title, answer, graspRate, difficultyRate } = enterObj;
            /* 如果为选择题，则录入 */
            if (type === 'choice') {
                const { option } = enterObj; // 获取选项内容
                wqb_questions.add({
                    data: {
                        type, // 题目类型
                        title, // 题目标题
                        option, // 选择题的选项
                        answer, // 答案
                        graspRate, // 题目掌握程度评分
                        difficultyRate, // 题目难易度评分
                        className, // 录入的课程名
                        gradeDesc, // 当前的年级名
                        gid, // 年级 id
                        uid, // 用户 id
                        creatDate: Date.now(), // 创建时间
                        changeTime: Number, // 修改时间
                    }
                }).then(async res => {
                    const { _id } = res; // qid
                    // 需要将此 _id (qid)，录入到数据库 wqb_grade 里对应的地方
                    const userGrade = await wqb_grade.doc(gid).get();
                    const { desc1, desc2 } = gradeDesc;
                    const { grade } = userGrade.data;
                    // 找到要添加课程的位置
                    grade.forEach(obj => {
                        // 找到第一层
                        if (obj.text === desc1) {
                            // 找到第二层
                            const { children } = obj;
                            children.forEach(obj2 => {
                                if (obj2.text === desc2) {
                                    obj2.class.forEach(obj3 => {
                                        if (obj3.name === className) {
                                            obj3.qidArr.push(_id);
                                        }
                                    })
                                }
                            })
                        }
                    });
                    wqb_grade.doc(gid).update({
                        data: {
                            grade,
                        }
                    });
                    reslove(res)
                })
            }
            /* 如果为判断题，则录入 */
            if (type === 'judgment' || type === 'fill' || type === 'explain' || type === 'other') {
                wqb_questions.add({
                    data: {
                        type, // 题目类型
                        title, // 题目标题
                        answer, // 答案
                        graspRate, // 题目掌握程度评分
                        difficultyRate, // 题目难易度评分
                        className, // 录入的课程名
                        gradeDesc, // 当前的年级名
                        gid, // 年级 id
                        uid, // 用户 id
                        creatDate: Date.now(), // 创建时间
                        changeTime: Number, // 修改时间
                    }
                }).then(async res => {
                    const { _id } = res; // qid
                    // 需要将此 _id (qid)，录入到数据库 wqb_grade 里对应的地方
                    const userGrade = await wqb_grade.doc(gid).get();
                    const { desc1, desc2 } = gradeDesc;
                    const { grade } = userGrade.data;
                    // 找到要添加课程的位置
                    grade.forEach(obj => {
                        // 找到第一层
                        if (obj.text === desc1) {
                            // 找到第二层
                            const { children } = obj;
                            children.forEach(obj2 => {
                                if (obj2.text === desc2) {
                                    obj2.class.forEach(obj3 => {
                                        if (obj3.name === className) {
                                            obj3.qidArr.push(_id);
                                        }
                                    })
                                }
                            })
                        }
                    });
                    wqb_grade.doc(gid).update({
                        data: {
                            grade,
                        }
                    });
                    reslove(res)
                })
            }
        }

        /* 场景为获取错题列表 */
        if (scene === 'GET_QUESTION') {
            const { getType, enterObj, uid } = event;
            switch (getType) {
                // 这个场景细分为，questionTotal 页面获取用户的所有错题
                case 'all':
                    var { skipNum, limitNum } = enterObj;
                    const allRes = await wqb_questions.where({
                        uid,
                    })
                        .skip(skipNum)
                        .limit(limitNum)
                        .get()
                    reslove(allRes);
                    break;
                // 这个场景细分为，questionTotal 页面根据gradeDesc分类获取用户的错题
                case 'grade':
                    var { skipNum, limitNum, gradeDesc } = enterObj;
                    const gradeRes = await wqb_questions.where({
                        uid,
                        gradeDesc,
                    })
                        .skip(skipNum)
                        .limit(limitNum)
                        .get()
                    reslove(gradeRes);
                    break;
                // 这个场景细分为，category页面根据课程名获取错题
                case 'class':
                    var { className, gradeDesc, skipNum, limitNum } = enterObj;
                    const classRes = await wqb_questions.where({
                        uid,
                        className,
                        gradeDesc
                    })
                        .skip(skipNum)
                        .limit(limitNum)
                        .get()
                    reslove(classRes);
                    break;
                // 这个场景细分为，exam页面随机抽取错题生成试卷
                case 'classExam':
                    var { className, gradeDesc } = enterObj;
                    let outObj = {}; // 输出10道选择题，5道填空，5道判断，1道问答题，1道其他题
                    wqb_questions
                        .aggregate()
                        .match({
                            uid,
                            className,
                            gradeDesc,
                            type: 'choice'
                        })
                        .sample({
                            size: 10
                        })
                        .end()
                        .then(res => {
                            // reslove(res.list);
                            outObj.choice = res.list;
                            wqb_questions
                                .aggregate()
                                .match({
                                    uid,
                                    className,
                                    gradeDesc,
                                    type: 'fill'
                                })
                                .sample({
                                    size: 5
                                })
                                .end()
                                .then(res2 => {
                                    outObj.fill = res2.list;
                                    wqb_questions
                                        .aggregate()
                                        .match({
                                            uid,
                                            className,
                                            gradeDesc,
                                            type: 'judgment'
                                        })
                                        .sample({
                                            size: 5
                                        })
                                        .end()
                                        .then(res3 => {
                                            outObj.judgment = res3.list;
                                            wqb_questions
                                                .aggregate()
                                                .match({
                                                    uid,
                                                    className,
                                                    gradeDesc,
                                                    type: 'explain'
                                                })
                                                .sample({
                                                    size: 1
                                                })
                                                .end()
                                                .then(res4 => {
                                                    outObj.explain = res4.list;
                                                    wqb_questions
                                                        .aggregate()
                                                        .match({
                                                            uid,
                                                            className,
                                                            gradeDesc,
                                                            type: 'other'
                                                        })
                                                        .sample({
                                                            size: 1
                                                        })
                                                        .end()
                                                        .then(res5 => {
                                                            // reslove(res.list);
                                                            outObj.other = res5.list;
                                                            reslove(outObj);
                                                        })
                                                })
                                        })
                                })
                        })
                    break;
            }
        }

        /* 场景为获取错题详情 */
        if (scene === 'GET_QUESTION_DETAIL') {
            const { qid } = event;
            const res = await wqb_questions.doc(qid).get();
            reslove(res)
        }

        /* 场景为删除一道错题 */
        if (scene === 'DEL_ONE_QUESTION') {
            const { qid, gid, gradeDesc, className } = event;
            // 同时需要将此 qid，在数据库 wqb_grade 里对应的地方删除
            const userGrade = await wqb_grade.doc(gid).get();
            const { desc1, desc2 } = gradeDesc;
            const { grade } = userGrade.data;
            // 找到要添加课程的位置
            grade.forEach(obj => {
                // 找到第一层
                if (obj.text === desc1) {
                    // 找到第二层
                    const { children } = obj;
                    children.forEach(obj2 => {
                        if (obj2.text === desc2) {
                            obj2.class.forEach(obj3 => {
                                if (obj3.name === className) {
                                    obj3.qidArr.forEach((item, index) => {
                                        if (item === qid) {
                                            obj3.qidArr.splice(index, 1);
                                        }
                                    })
                                }
                            })
                        }
                    })
                }
            });
            wqb_grade.doc(gid).update({
                data: {
                    grade,
                }
            }).then(async (res1) => {
                // 在wqb_questions中删除
                const res2 = await wqb_questions.doc(qid).remove();
                reslove(res2);
            })
        }

        /* 场景为清空改课程下所有错题 */
        if (scene === 'DEL_ALL_QUESTION') {
            const { gid, gradeDesc, className } = event;
            const userGrade = await wqb_grade.doc(gid).get();
            const { desc1, desc2 } = gradeDesc;
            const { grade } = userGrade.data;
            // 找到要添加课程的位置
            grade.forEach(obj => {
                // 找到第一层
                if (obj.text === desc1) {
                    // 找到第二层
                    const { children } = obj;
                    children.forEach(obj2 => {
                        if (obj2.text === desc2) {
                            obj2.class.forEach(obj3 => {
                                if (obj3.name === className) {
                                    obj3.qidArr = [];
                                }
                            })
                        }
                    })
                }
            });
            wqb_grade.doc(gid).update({
                data: {
                    grade,
                }
            }).then(async (res1) => {
                // 在wqb_questions中删除
                const res2 = await wqb_questions.where({
                    gradeDesc,
                    className,
                }).remove();
                reslove(res2);
            })
        }

        /* 场景为修改错题信息 */
        if (scene === 'EDIT_QUESTION') {
            let res;
            const { qid, enterObj, isChoice } = event;
            const { title, difficultyRate, graspRate, answer } = enterObj;
            // 需要判断一下是不是选择，与其他题目修改不同
            if (!isChoice) {
                res = await wqb_questions.doc(qid).update({
                    data: {
                        title,
                        answer,
                        difficultyRate,
                        graspRate,
                        changeTime: Date.now(),
                    }
                });
            } else {
                const { opt1, opt2, opt3, opt4 } = enterObj;
                res = await wqb_questions.doc(qid).update({
                    data: {
                        title,
                        difficultyRate,
                        graspRate,
                        answer,
                        option: [
                            { opt: 'A', cent: opt1 },
                            { opt: 'B', cent: opt2 },
                            { opt: 'C', cent: opt3 },
                            { opt: 'D', cent: opt4 },
                        ],
                        changeTime: Date.now(),
                    }
                })
            }
            reslove(res);
        }

        /* 场景为获取用户错题的数量 */
        if (scene === 'GET_QUESTION_COUNT') {
            const { uid } = event;
            const res = await wqb_questions.where({
                uid,
            }).count();
            reslove(res);
        }

        //获取此用户，近期的20条错题信息
        if (scene === 'GET_APPOINT_USER_QUESTION') {
            const { skipNum, limitNum, uid } = event;
            const res = await wqb_questions.where({
                uid,
            })
                .orderBy('creatDate', 'desc')
                .skip(skipNum)
                .limit(limitNum)
                .get()
            reslove(res);
        }

        //获取此用户，七天内或30天内的错题信息
        if (scene === 'GET_AGO_TIME_QUESTION') {
            const { uid, agoTime } = event;
            const res = await wqb_questions.where({
                uid,
                creatDate: _.gt(agoTime),
            }).get()
            reslove(res);
        }

        // 获取所有错题信息，拿出来根据题目分类，进行饼状图的绘制
        if (scene === 'GET_ALL_PIE_QUESTION') {
            const { uid } = event;
            wqb_questions.aggregate()
                .match({
                    uid,
                })
                .group({
                    _id: '$type',
                    num: $.sum(1)
                })
                .end()
                .then(res => {
                    reslove(res);
                })
                .get()
        }

        // 获取昨天一天内发布的错题，为今日待复习模块取出数据
        if (scene === 'GET_YESTARDAY_QUESTION') {
            const { uid, startTime, overTime, gradeDesc } = event;
            const res = wqb_questions.where({
                uid,
                gradeDesc,
                creatDate: _.and(_.gt(startTime), _.lt(overTime)),
            }).get();
            reslove(res)
        }

        // 点亮错题，点亮即标记，把不会的印象不深的错题点亮后，可以在每日复习中复习它
        if (scene === 'AGREE_LIGHT_QUESTION') {
            const { qid } = event;
            wqb_questions.doc(qid).update({
                data: {
                    light: true,
                }
            }).then(res => {
                reslove(res);
            })
        }

        // 取消点亮错题
        if (scene === 'CANCEL_LIGHT_QUESTION') {
            const { qid } = event;
            wqb_questions.doc(qid).update({
                data: {
                    light: false,
                }
            }).then(res => {
                reslove(res);
            })
        }

        // 获取标记的错题
        if (scene === 'GET_MY_LIGHT_QUESTION') {
            const { uid, gradeDesc } = event;
            const res = wqb_questions.where({
                uid,
                gradeDesc,
                light: true,
            }).get();
            reslove(res)
        }

    });
}